package com.xh.bussiness.resource.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageUtil {

    private static Integer DEFAULT_HEIGHT = 120;
    private static Integer DEFAULT_WIDTH = 160;

    public static void getZoomImg(String inpath, String outpath,Integer height,Integer width){
        if(null == height){
            height = DEFAULT_HEIGHT;
        }
        if(null == width){
            width = DEFAULT_WIDTH;
        }

        //定义一个BufferedImage对象，用于保存缩小后的位图
        BufferedImage bufferedImage=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics graphics=bufferedImage.getGraphics();

        //读取原始位图
        Image srcImage= null;
        try {
            srcImage = ImageIO.read(new File(inpath));
            //得到源图宽
            int imageWidth = srcImage.getWidth(null);
            //得到源图长
            int imageHeight = srcImage.getHeight(null);

            double sx = (double) width / imageWidth;
            double sy = (double) height / imageHeight;

            // 等比缩放
            if (sx > sy) {
                sx = sy;
                width = (int) (sx * imageWidth);
            } else {
                sy = sx;
                height = (int) (sy * imageHeight);
            }



            //将原始位图缩小后绘制到bufferedImage对象中
            graphics.drawImage(srcImage,0,0,width,height,null);
            //将bufferedImage对象输出到磁盘上
            ImageIO.write(bufferedImage,"png",new File(outpath));
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
